package pers.xiaojun.boot.module.system.dao.redis;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import pers.xiaojun.boot.common.config.properties.CaptchaProperties;
import pers.xiaojun.boot.module.system.constants.RedisKeyConstants;
import pers.xiaojun.boot.module.system.controller.captcha.vo.CaptchaRespVO;

import java.util.concurrent.TimeUnit;

/**
 * 验证码数据访问层
 *
 * @author xiaojun
 * @since 2025-10-06
 */
@Repository
@RequiredArgsConstructor
public class CaptchaRedisDAO {

    private final RedisTemplate<String, Object> redisTemplate;
    private final CaptchaProperties captchaProperties;

    /**
     * 保存验证码至 redis
     *
     * @param captchaKey   验证码 Key
     * @param captchaValue 验证码 Value
     */
    public void save(String captchaKey, String captchaValue) {
        redisTemplate.opsForValue().set(
                formatCaptchaKey(captchaKey),
                captchaValue,
                captchaProperties.getExpiresIn(),
                TimeUnit.SECONDS
        );
    }

    /**
     * 根据验证码Key获取值
     *
     * @param captchaKey 验证码key
     * @return 验证码Value
     */
    public String getValueByKey(String captchaKey) {
        Object result = redisTemplate.opsForValue().get(formatCaptchaKey(captchaKey));
        if (result == null) {
            return null;
        }
        return (String) result;
    }

    /**
     * 根据验证码key删除验证码
     *
     * @param captchaKey 验证码key
     */
    public void deleteByKey(String captchaKey) {
        redisTemplate.delete(formatCaptchaKey(captchaKey));
    }

    /**
     * 格式化验证码Key
     *
     * @return 验证码Key
     */
    private String formatCaptchaKey(String captchaKey) {
        return StrUtil.format(RedisKeyConstants.Captcha.IMAGE_CAPTCHA, captchaKey);
    }

}
